package com.sinog.front.util;

import com.sinog.core.utilbean.Constants;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc solr工具类
 * @author lzq
 * @date 2020-08-31 5:37 下午
 */
public final class SolrUtil {

    /**
     * 描述
     * @param client client
     * @param solrQuery solrQuery
     * @param param param
     * @return Map<String,Object>
     */
    public static Map<String,Object> baseQueryBase(HttpSolrClient client,SolrQuery solrQuery,Map<String,Object> param) throws org.apache.solr.client.solrj.SolrServerException, java.io.IOException {
        Map<String,Object> result = new HashMap<>(16);
        List<Map<String,Object>> list = new ArrayList<>(16);
        if(null != param) {
            //排序
            if(null != param.get(Constants.StrFinalValue.SORTFIELD) && !"".equals(param.get(Constants.StrFinalValue.SORTFIELD))) {
                String order = null == param.get("sortOrder") ? "asc" : param.get("sortOrder").toString();
                if(Constants.StrFinalValue.DESC.equalsIgnoreCase(order)) {
                    solrQuery.addSort(param.get("sortField").toString(),SolrQuery.ORDER.desc);
                } else {
                    solrQuery.addSort(param.get("sortField").toString(),SolrQuery.ORDER.asc);
                }
            }
            //分页
            if(null == solrQuery.getStart() && null == solrQuery.getRows()) {
                //设置起始值
                solrQuery.setStart(Integer.parseInt(param.get("start").toString()));
                solrQuery.setRows(Integer.parseInt(param.get("pageSize").toString()));
            }
        }
        QueryResponse response = client.query(solrQuery);
        //获取文档集合
        SolrDocumentList results = response.getResults();
        //获取总命中数
        long total = results.getNumFound();
        for(SolrDocument doc : results) {
            Map<String,Object> map = new HashMap<>(16);
            Map<String,Object> valMap = doc.getFieldValueMap();
            for(String c : valMap.keySet()) {
                if("idnum".equals(c)) {
                    String idNumNew = Sm4.decryptEcb("",doc.get(c).toString());
                    doc.put(c,idNumNew);
                }
                map.put(c,doc.get(c));
            }
            list.add(map);
        }
        result.put("total",(int)total);
        result.put("data",list);
        return result;
    }
}